﻿Imports System.Windows
Imports System.Activities
Imports System.Activities.Expressions
Imports System.Activities.Presentation.Model
Imports Microsoft.VisualBasic.Activities

Public Class ActivityImageConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If Not TypeOf value Is ModelItem Then Return Nothing
        Dim result As DrawingBrush = Nothing

        Dim inArgs = TryCast(DirectCast(value, ModelItem).GetCurrentValue, InArgument(Of String))
        If inArgs Is Nothing Then Return Nothing

        Dim exp = inArgs.Expression
        Dim vbexp = TryCast(exp, VisualBasicValue(Of String))
        Dim lite = TryCast(exp, Literal(Of String))

        Dim impValue = ""
        If lite IsNot Nothing Then
            impValue = lite.Value
        ElseIf vbexp IsNot Nothing Then
            impValue = vbexp.ExpressionText
        End If

        Dim target = IO.Path.GetFullPath(impValue)
        If Not IO.File.Exists(target) Then Return Nothing

        Dim fileData As New BitmapImage()
        fileData.BeginInit()
        fileData.UriSource = New Uri(target)
        fileData.EndInit()

        Return fileData
    End Function

    Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Dim vbarg As New VisualBasicValue(Of String)(value.ToString)
        Dim inArgs As New InArgument(Of String)(vbarg)
        Return inArgs
    End Function
End Class
